const app = getApp()
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'


Page({
  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {
      avatarUrl: defaultAvatarUrl
    },
  },

  onChooseAvatar(e) {
    console.log(e);
    const {
      avatarUrl
    } = e.detail

    let userInfo = this.data.userInfo
    userInfo.avatarUrl = avatarUrl
    this.setData({
      userInfo: userInfo,
    })
    console.log(app.globalData.userInfo);
  },

  formSubmit(e) {
    let nickName = e.detail.value.nickname
    let userInfo = this.data.userInfo
    userInfo.nickName = nickName
    this.setData({
      userInfo: userInfo,
    }, () => {
      this.submit()
    })
  },

  submit() {
    let userInfo = this.data.userInfo
    wx.setStorageSync('userInfo', userInfo)
    // 登陆方法
    wx.showLoading({
      title: '加载中',
    })
    wx.cloud.callFunction({
      name: 'nine_thirth',
      config: {
        env: app.globalData.env
      },
      data: {
        cloud_function: "updateUserInfo",
        openid: wx.getStorageSync('openid'),
        nickName: userInfo.nickName,
        avatarUrl: userInfo.avatarUrl
      }
    }).then((resp) => {
      console.log("信息：", resp)
      let data = resp.result.data
      if (data.status == 200) {
        wx.showToast({
          title: data.message,
          icon: 'none'
        })
      } else {
        wx.showToast({
          title: data.message,
          icon: 'none'
        })
      }
      wx.hideLoading()
    }).catch((e) => {
      console.error('获取数据失败:', e);
      wx.hideLoading()

    });
    wx.navigateBack()
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  onShow() {
    let userInfo = wx.getStorageSync('userInfo')
    if (userInfo && userInfo !== '') {
      this.setData({
        userInfo: userInfo
      })
    }
  },
})